<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\controller\api;

use app\model\Menu as MenuModel;

/**
 * @title 菜单接口
 * @description 用户菜单接口
 * @group 用户
 * @header authorization:接口授权
 */
class Menu extends Api {

	protected $middleware = ['Api'];

	/**
	 * @title 菜单列表
	 * @description 获取菜单列表数据，数据为tree类型
	 */
	public function lists(MenuModel $menu){
		$res = $menu->order('sort asc, id desc')->select();
		$list = list_to_tree($res->toArray(), 'id', 'pid', 'children');

		$this->data['code'] = 0;
		$this->data['data'] = $list;
		return $this->data;
	}

	/**
	 * @title 添加菜单
	 * @description 添加菜单接口
	 */
	public function add(MenuModel $menu){
		$data = $this->request->param();
		$result = $menu->save($data);
		if (false !== $result) {
			$this->data['code'] = 0;
			$this->data['msg'] = '添加成功！';
		}else{
			$this->data['code'] = 1;
		}
		return $this->data;
	}

	/**
	 * @title 修改菜单
	 * @description 更加菜单ID修改菜单接口
	 */
	public function edit(MenuModel $menu){
		$data = $this->request->param();
		$result = $menu->where('id', $data['id'])->save($data);
		if (false !== $result) {
			$this->data['code'] = 0;
			$this->data['msg'] = '修改成功！';
		}else{
			$this->data['code'] = 1;
		}
		return $this->data;
	}

	/**
	 * @title 菜单删除
	 * @description 根据菜单ID对菜单进行删除，永久删除
	 */
	public function delete(MenuModel $menu){
		$param = $this->request->param();
		if (isset($param['id']) && $param['id']) {
			if (is_array($param['id'])) {
				$map[] = array('id', 'in', $param['id']);
			}else{
				$map['id'] = $param['id'];
			}
			$result = $menu->where($map)->delete();
			if (false !== $result) {
				$this->data['code'] = 0;
				$this->data['msg'] = "删除成功！";
			}else{
				$this->data['code'] = 1;
				$this->data['msg'] = "删除失败！";
			}
		}else{
			$this->data['code'] = 1;
			$this->data['msg'] = "非法操作！";
		}
		return $this->data;
	}

	/**
	 * @title 菜单详情
	 * @description 根据菜单ID获取菜单详细信息
	 */
	public function detail(MenuModel $menu){
		$id = $this->request->param('id', '');
		if (!$id) {
			$this->data['code'] = 1;
			$this->data['msg'] = '非法操作！';
		}else{
			$info = $menu->where('id', $id)->find();
			$this->data['code'] = 0;
			$this->data['data'] = $info->toArray();
		}
		return $this->data;
	}
}